import axios from 'axios'

const instance = axios.create({
  baseURL: window.serverConfig.VUE_APP_HOST_URL
})
instance.interceptors.request.use((config) => {
  if (localStorage.getItem('token')) {
    config.headers['token'] = localStorage.getItem('token')
  }
  return config
}, (error) => Promise.reject(error))

instance.interceptors.response.use((response) => {
  if (!window.localStorage.getItem('token')) {
    window.localStorage.setItem('token', response.data.result.token)
  }

  if (response.data.status === 'fail') {
    return Promise.reject(response.data.msg)
  }
  return response.data
}, (error) => Promise.reject(error))

export default instance
